package com.example.demo33.service;

import com.example.demo33.entity.PriceBatchResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.*;
import java.util.*;

@Service
public class PriceService {

    @Value("${csqaq.api.base-url}")
    private String apiBaseUrl;

    @Value("${csqaq.api.token}")
    private String apiToken;

    private final RestTemplate restTemplate;
    private String API_BASE_URL = apiBaseUrl;
    private  String API_TOKEN = apiToken;

    public PriceService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Cacheable(value = "itemPrices", key = "#marketHashNames", sync = true)
    public PriceBatchResponse getBatchPrices(List<String> marketHashNames) {
        return fetchPricesFromApi(marketHashNames);
    }

    private PriceBatchResponse fetchPricesFromApi(List<String> marketHashNames) {

            String url = API_BASE_URL + "/api/v1/goods/getPriceByMarketHashName";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("ApiToken", API_TOKEN);

            Map<String, List<String>> requestBody = new HashMap<>();
            requestBody.put("marketHashNameList", marketHashNames);

            HttpEntity<Map<String, List<String>>> request = new HttpEntity<>(requestBody, headers);

            ResponseEntity<PriceBatchResponse> response = restTemplate.exchange(
                    url, HttpMethod.POST, request, PriceBatchResponse.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                return response.getBody();
            } else {
                throw new RuntimeException("API请求失败: " + response.getStatusCode());
            }

    }
}